<!--  -->
<template>
    <div>
        <van-form @submit="changeFromData" @failed="failedMethod">

            <!-- 头 -->
            <div class="font15 mt10 pl10">
                <span class="titletext">{{ nFromdata.title }}</span>
                <div class="graytext mt10 font13">
                    <span>表单编号：</span>
                    <span class="titletext">{{ nFromdata.pmInsId }}</span>
                </div>
            </div>


            <van-tabs v-model="active" color="#1989fa" sticky animated :lazy-render	="false" line-width="33%" offset-top="50">

                <van-tab title="基础信息">
                    <xf-table-one ref="toMsgs" :fromdata='fromdata' :showHistory='showHistory' :approveList='approveList'
                        :historydata='historydata' :workItemName="params.workItemName" :pmInsType="params.pmInsType" :location="params.location" :todoType='todotype' @freshDat='freshData($event)' :showZizhuInfos='showZizhuInfos'/>
                </van-tab>

                <van-tab title="其他信息">
                    <xf-table-two ref="tableTwo" :fromdata='fromdata' :mergeAbilityInfoMode="mergeAbilityInfoMode" :zhenbieData="zhenbieData" :location="params.location" :pmInsType="params.pmInsType" :todoType='todotype' :canPingfen='canPingfen'/>
                </van-tab>
            </van-tabs>


            <!-- 跳转意见 -->
            <div class="left_botton">
                <button block type="button" @click="tomsg()" style="color:#60a9ec; display: inline-block;width:100%; border: 0px solid #60a9ec; border-radius: 15px 0px 0px 15px;
            padding:10px 10px 10px 15px; font-size:13px">意见</button>
            </div>


            <!-- 流转下一步 -->
            <div v-if="todotype||toRead" class="footer">
                <van-button block type="info" native-type="submit" :disabled="!canToNext"
                    style="display: inline-block; width: 100%; border: 0px solid #60a9ec">{{ buttonTitle }}</van-button>
            </div>

        </van-form>

    </div>
</template>



<script>
import {
  getFormDetail,
  getDecisionMakingByPmInsId,
  getWfLinkTracks,
  getWfOptMags,
  findAllNoPage,
  getLocationNameById, fileParsingRequestAnalysisFlowQuery, getPublicCountyCode, getMergeAbilityInfoList,
} from "@/api/dictapi";

import { mapGetters } from "vuex";
import { Notify, Dialog, Toast } from "vant";
import { openFileUrl } from "@/store/openFile";
import util from "@/assets/js/public";

import XfTableOne from './xfTableOne.vue';
import XfTableTwo from './xfTableTwo.vue';



export default {
    components: { XfTableOne, XfTableTwo },
    data() {
        return {
            showZizhuInfos:false,
            canPingfen:false,
            fromdata: {},
            mergeAbilityInfoMode:{},
            nFromdata: {},
            zhenbieData: [],

            showHistory: false,
            historydata: {},
            approveList: [],

            params: this.$route.query,
            todotype: false,
            toRead: false,
            buttonTitle: '流转下一步',
            canToNext: true,
            active: 0,

            xsHasAlert: false,   /// 县、市 提示弹窗环节
            aiDataResult:{}
        };
    },
    computed: {
        ...mapGetters(["user"]),
        ...mapGetters(["userinfo"]),
    },

    //生命周期--创建完成
    created() {
        if(this.params.pmInsType==null&&this.params.processType!=null) {
          this.params.pmInsType = this.params.processType
        }
        if (this.params.todoType == "1") {
            this.todotype = true;
        }
        else if (this.params.todoType == "2") {
            this.showHistory = true;
        }else if (this.params.todoType == "3") {
            this.toRead = true;
        }

        if (this.params.location == 'dict.start' ||
            this.params.location == 'dict.startToCountyLeader' ||
            this.params.location == 'dict.leadershipToDelivery' ||
            this.params.location == 'dict.cityLeadToCityDeliveryAdmin' ||
            this.params.location == 'dict.specialToIndustryAdmin'||
            this.params.location == 'dict.noAgree') {
                
            this.canToNext = false;
            this.buttonTitle = '暂不支持该环节,请至PC端办理';
        }
        if (this.params.location == 'dict.leadershipToDelivery') {
            this.showZizhuInfos = true;
        }else {
            this.showZizhuInfos = false;
        }
        if (this.params.location == 'dict.cityLeaderToCityDeliveryAdmin') {
          this.canPingfen = true;
        }else {
          this.canPingfen = false;
        }
    },

    //生命周期--挂载完成
    mounted() { 
        console.log(0,this.$refs);

        this.getdetail();

    },

    //方法调用
    methods: {
      freshData(value) {
        console.log("父页面的数据刷新", this.canEdit)
        if (localStorage.getItem('itListNumber') != '{}' && localStorage.getItem('itListValue')) {
          this.fromdata.deliverComplex = JSON.parse(localStorage.getItem('itListNumber'))
          this.fromdata.autonomousImplementionType = JSON.parse(localStorage.getItem('itListValue'))
          if (JSON.parse(localStorage.getItem('itListIsZiZhu'))=="1"){
            this.fromdata.autonomousImplemention = "是"
          }else {
            this.fromdata.autonomousImplemention = "否"
          }
          localStorage.setItem('itListNumber', '{}')
          localStorage.setItem('itListValue', '{}')
          localStorage.setItem('itListIsZiZhu', '{}')
        }
      },
        failedMethod(data) {

            console.log('submit fail:', data);
            const errorArr = data.errors;
            const errorObj = errorArr[0];
            const errorMessage = errorObj.message;
            Toast({ type: 'text', message: errorMessage, duration: 1000 });
        },

        tomsg() {
            this.active = 0;
            setTimeout(() => {
                document.getElementById('opinion').scrollIntoView({ behavior: 'smooth' });
            }, 350)

        },

        openFileUrlfun(value) {
            this.$router.push({
                name: "fileview",
                query: {
                    openFileUrl: openFileUrl(value),
                },
            });
        },

        // 获取详情数据
        getFromData() {
            Toast.loading({ message: "加载中", forbidClick: false, });
            getDecisionMakingByPmInsId(Object.assign(this.params, { userName: this.user.userName })).then((result) => {

                this.fromdetal = {};
                Toast.clear();
                if (!result.data) {
                    Notify(result.message);
                    return;
                }

                if (result.data.data) {

                    this.fromdata = result.data.data;
                    console.log(this.fromdata)
                    this.$nextTick().then(() => {
                        this.$refs.toMsgs.checkMeetingsAndCB(this.params.workItemName)
                        this.$refs.tableTwo.configFromData()

                        var hasAlert = this.$refs.toMsgs.hasAlert;
                        if (hasAlert) {
                            Dialog.alert({ title: "提示", message: "如需选择关联会议纪要，请至PC端办理" }).then(() => { });
                        }
                    })

                    this.getRHNLZBMessage(this.fromdata.businessId);
                    this.getPublicCountyCode();
                    if (this.fromdata?.mergeAbilityInfoMode){
                      this.mergeAbilityInfoMode=this.fromdata.mergeAbilityInfoMode
                    }else {
                      this.getMergeAbilityInfoList();
                    }
                }

            });
        },
        getPublicCountyCode() {
          getPublicCountyCode({userName:this.user.userName,city:this.fromdata.city})
              .then((result)=>{
                Toast.clear();
                if(!result.data){
                  Notify(result.message);
                  return;
                }
                if(result.data.data){
                  let cityList=result.data.data
                  for (let i in cityList){
                    if (cityList[i].value==this.fromdata.publicCountyCode){
                      this.fromdata={...this.fromdata,...{publicCountyCodeValue:cityList[i].name}}
                      break
                    }
                  }
                }
              })
        },
        getMergeAbilityInfoList() {
          getMergeAbilityInfoList({userName:this.user.userName,businessId:this.fromdata.businessId})
              .then((result)=>{
                Toast.clear();
                if(!result.data){
                  Notify(result.message);
                  return;
                }
                if(result.data.data){
                  this.mergeAbilityInfoMode=result.data.data[0]
                }
              })
        },
        getdetail() {
            Toast.loading({ message: "加载中", forbidClick: false, });
            getFormDetail(Object.assign(this.params, { userName: this.user.userName })).then((result) => {
                this.fromdetal = {};
                Toast.clear();
                if (!result.data) {
                    Notify(result.message);
                    return;
                }

                if (result.data.data) {
                    this.nFromdata = result.data.data;
                }
            });

            getLocationNameById(Object.assign(this.params, { userName: this.user.userName })).then((result) => {

                if (!result.data) {
                    Notify(result.message);
                    return;
                }

                if (result.data.data) {

                    this.params.workItemName = result.data.data.workItemName;
                    this.getFromData();
                }
            });

            

            getWfOptMags(Object.assign(this.params), {  userName: this.user.userName }).then((result) => {
                Toast.clear();
                if (!result.data) {
                    Notify(result.message);
                    return;
                }
                this.approveList = result.data.data.reverse();
            });

            if (this.showHistory) {
                getWfLinkTracks(Object.assign(this.params), {
                    userName: this.user.userName,
                }).then((result) => {
                    Toast.clear();
                    if (!result.data) {
                        Notify(result.message);
                        return;
                    }

                    this.showHistory = false;
                    if (result.data.data) {
                        //数据过滤，并生成新的数组
                        this.historydata = result.data.data.filter((item) => item.CURRENTSTATE == 10)[0];
                        if (this.historydata) {
                            if (this.historydata.MANAGER) {
                                this.showHistory = true;
                            }
                        }
                    }
                });
            }
        },

        /// 融合能力甄别
        getRHNLZBMessage(value) {
          Toast.loading({ message: "加载中", forbidClick: false, });
            findAllNoPage(Object.assign(this.params, { userName: this.user.userName, businessId: value })).then((result) => {
                this.fromdetal = {};
                Toast.clear();
                if (!result.data) {
                    Notify(result.message);
                    return;
                }
                if (result.data.data) {
                    this.zhenbieData = result.data.data;
                    if(this.zhenbieData == null) {
                        this.zhenbieData = [];
                    }
                }
                if(this.fromdata.makingOpinionsFileList){
                  this.getAIdata()
                }
            });
        },
        getAIdata(){
          Toast.loading({ message: "加载中", forbidClick: false, });
          fileParsingRequestAnalysisFlowQuery(Object.assign(this.params, { userName: this.user.userName, fileId: this.fromdata.makingOpinionsFileList[0].id })).then((result) => {
            Toast.clear();
            if (!result.data) {
              Notify(result.message);
              return;
            }
            if (result.data.data) {
              this.aiDataResult = result.data.data;
            }
          });
        },
        /// 
        changeFromData() {
            if(this.canPingfen){
              if (!this.fromdata.deliverComplex){
                Notify("请对项目交付复杂度进行打分")
                return
              }
              if (this.fromdata.autonomousImplemention == '是'&&!this.fromdata.autImplementScope){
                Notify("请选择自主实施范围")
                return
              }
              if (!this.fromdata.onProjectGrade){
                Notify("请点击售中售后阶段项目预定级评分")
                return
              }
            }
            var formSendData = { "htmlParamMap": {} };
            formSendData.htmlParamMap = this.fromdata;
            formSendData.id = this.nFromdata.id;
            formSendData.pmInsId = this.nFromdata.pmInsId;
            formSendData.processType = this.params.pmInsType
            formSendData.workItemId = this.params.workItemId;

            var decisionLevel = this.fromdata.decisionLevel;
            var isDecision = '0'; 
            if (decisionLevel == '省公司分管副总签批决策' || 
                '省公司DICT项目管理委员会决策' == decisionLevel || 
                '省公司总办会决策' == decisionLevel) {
                isDecision = '1';
            }

            

            var params1 = {
                kv: {
                    'currentUserCode': util.encrypt(this.params.userName),
                    'source': 'MOBILE',
                    'location': this.params.location,
                    'processInstId': this.params.processInstId,
                    'processDefName': this.params.processDefName,
                    'processType': this.params.pmInsType,
                    'isDecision': isDecision,
                },
            };

            var params2 = {
                kv: {
                    "currentUserCode": util.encrypt(this.params.userName),
                    "source": 'MOBILE',
                    "location": this.params.location,
                    "processInstId": this.params.processInstId,
                    'processType': this.params.pmInsType,
                    'receiptCode': this.params.processInstId,
                    'provinceSupport': this.fromdata.provinceSupport,
                },
            };

            var params3 = {
                kv: {
                    "source": 'MOBILE',
                    "currentUserCode": util.encrypt(this.params.userName),
                    "workItemId": this.params.todoType==3?"":this.params.workItemId,
                    "processInstId": this.params.processInstId,
                    "location": this.params.location,
                     "notificationId":this.params.todoType==3?this.params.wfnid:""
                },
            };


            /// 承办模块 当前可操作的
            var isCityOrProvince = null;
            var canEditDSCB = this.$refs.toMsgs.canEditDSCB;
            var canEditSGSCB = this.$refs.toMsgs.canEditSGSCB;
            if (canEditDSCB) {
                isCityOrProvince = 'city';
            }

            if (canEditSGSCB) {
                isCityOrProvince = 'province';
            }

            const decisionSummaryFileList = this.$refs.tableTwo.getNewFromdata('decisionSummaryFileList');
            this.fromdata.decisionSummaryFileList = decisionSummaryFileList;
            localStorage.setItem('submitPageParam', JSON.stringify({
                    getDecisionsUrl: 'decisionAndUser$api$getDecisions',
                    getUserUrl: 'decisionAndUser$api$getOrgAndUser',
                    tosubmintUrl: 'applicationFormEnhance$api$startSubmitProcess',

                    getDecisionsParams: params1,
                    getUserParams: params2,
                    tosubmintParams: params3,
                    formData: formSendData,

                    cityDecision: this.fromdata.cityDecision,
                    provinceDecision: this.fromdata.provinceDecision,
                    isCityOrProvince: isCityOrProvince,
                    fromMoa:this.params.fromMoa,
                    type:this.params.todoType==3?"toRead":"toDo"
                }));
            this.$router.push({
                name: "srqrsubmit"
            });
        },
    },
};
</script>
<style  scoped>
/* @import url();*/
</style>